<template>
  <div class="monitor-data">
    <div class="search-panel">
      <el-form :inline="true" :model="form" class="search-panel--left" @submit.native.prevent>
        <el-form-item>
          <tree-select
              ref="treeSelect"
              :width="220"
              :checkedKeys="checkedKeys"
              placeholder="请选择地区"
              :text-formatter="val => `${val ? val.text : ''}`"
              :data="areaList"
              @change="change"
              :defaultProps="{
                id: 'id',
                children: 'children',
                label: 'text'
              }">
        </tree-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
              v-model="taskId"
              filterable 
              clearable
              @change="changeTask"
              placeholder="请选择任务">
              <el-option
                v-for="item in taskList"
                :key="item.taskId"
                :label="item.taskName"
                :value="item.taskId">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <div class="left">
        <main-map height="500px"   @map-loaded="mapLoaded" :showSearchInput="false"></main-map> 
      </div>
       <div class="right">
          <main-table
          height="500"
          ref="table"
          :data="list"
          :columns="columns"
          :columnType="['index']"
          border>

              <template slot-scope="scope" :slot="item.prop"
               v-for="(item,index) in (columns.filter(v => v.prop !== 'code'))">
                  <span :title="scope.row[item.prop+'dataValue']"  :key="index">{{ scope.row[item.prop] }}</span>
              </template>   
        </main-table>
       </div>
    </div>
  </div>
</template>
<script>
export default {
  components: {

  },
  data() {
    return {
      form: {
        taskCode: '',
        equipCodeList: [],
        pointCode: '',
        polluteCodeList: []
      },
      checkedKeys: [],
      areaList: [],
      areaCode: '',
      pointCode: '',
      startTime: this.$moment().add(-7, 'd').format('YYYY-MM-DD 00:00:00'),
      endTime: this.$moment().format('YYYY-MM-DD HH:mm:ss'),
      taskId: '',
      pointList: [],
      taskList: [],
      showLayer: false,
      loading: false,
      tableData: [],
      list: [],
      pageNum: 1,
      pageSize: 20,
      map: null,
      AMap: null,
      infoWindow: null,
      AMapUI: null,
      point: {},
      columns: [
        { label: '样本编码', prop: 'code' }

      ]
    };
  },
  computed: {

  },
  methods: {
    mapLoaded(map, AMap) {
      this.map = map;
      this.AMap = AMap;
      this.drawBounds();
    },
    change(val) {
      if (val) {
        this.areaCode = val.id;
        this.taskId = '';
        this.getTaskList();
      }
    },
    changeTask(val) {
      if (val) {
        const o = this.taskList.find(v => v.taskId === val);
        this.point = o;
        this.form.taskCode = o ? o.taskCode : '';
        this.addMarker();
        this.addInforWindow();
      }
    },
    drawBounds() {
      const AMap = this.AMap;
      const map = this.map;
      var opts = {
        subdistrict: 0, // 获取边界不需要返回下级行政区
        extensions: 'all', // 返回行政区边界坐标组等具体信息
        level: 'province' // 查询行政级别为 市
      };
      const district = new AMap.DistrictSearch(opts);
      district.search('江苏省', function(status, result) {
        var polygons = [];
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            // 生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.4,
              fillColor: '#80d8ff',
              strokeColor: '#0091ea'
            });
            polygons.push(polygon);
          }
        }
        map.add(polygons);
        map.setFitView(polygons);// 视口自适应
      });
    },
    getAreaList() {
      const params = {
        url: `/api/ems/area/childlist`,
        type: 'post',
        params: {}

      };
      this.$ajax(params).then(resp => {
        const { result, rows } = resp;
        if (result) {
          this.areaList = rows;
        }
      });
    },
    getTaskList() {
      const params = {
        url: `/api/ems/task/list`,
        type: 'post',
        params: {
          areaCode: this.areaCode,
          startTime: this.startTime,
          endTime: this.endTime
        }
      };
      this.$ajax(params).then(resp => {
        const { result, rows } = resp;
        if (result) {
          this.taskList = rows;
        }
      });
    },
    search() {
      this.getDataList();
    },
    addMarker() {
      const point = this.point;
      const AMap = this.AMap;
      const offset = new AMap.Pixel(-16, -30);
      const marker = new AMap.Marker({
        clickable: true, // 点位是否可点击
        offset, // 设置点标记偏移量
        position: [point.longi, point.lat], // new AMap.LngLat(point.longitude, point.latitude),
        content: this.getMarkContent(point),
        extData: point
      });
      this.map.add([marker]);
    },
    addInforWindow() {
      const point = this.point;
      if (!this.infoWindow) {
        this.infoWindow = new AMap.InfoWindow({
        // anchor: 'bottom-center',
          content: '这是信息窗体！这是信息窗体！',
          offset: new AMap.Pixel(0, -30)
        });
      }
      const html = `
      <p>${point.pointName}</p>
      <p>任务名称：${point.taskStatus}</p>
      <p>任务点位：${point.placeName}</p>
      <p>任务要求：${point.requirement}</p>
      `;
      this.infoWindow.setContent(html);
      this.infoWindow.open(this.map, [point.longi, point.lat]);
    },
    getMarkContent(point) {
      // 是否超期 0 否 1 是
      // private Integer isOverdue;
      const color = point.isOverdue === 1 ? 'red' : '#67C23A';
      return `<svg class="car-icon" style="color:${color};" aria-hidden="true" ><use xlink:href="#icon-xiaoche"></use></svg>`;
    },
    getDataList() {
      // 查询应急监测数据列表
      const params = {
        url: `/api/ems/data/list`,
        type: 'post',
        params: this.form
      };
      this.loading = true;
      this.$ajax(params).then(resp => {
        this.loading = false;
        const { result, rows } = resp;
        if (result) {
          this.tableData = rows;

          if (rows.length) {
            const dataList = rows[0].dataList;
            const columns = dataList.map(item => {
              return { label: item.polluteName, prop: item.polluteCode };
            });
            this.columns = [
              { label: '样本编码', prop: 'code' },
              ...columns
            ];
          }

          this.list = rows.reduce((item, next) => {
            const o = next.dataList.reduce((a, b) => {
              a[b.polluteCode] = b.dataValuePre;
              a[b.polluteCode + 'dataValue'] = b.dataValue;
              return a;
            }, {
              code: next.sampleCode
            });
            item.push(o);
            return item;
          }, []);
          console.log(`      this.columns `, this.columns);
          console.log(`      this.list `, this.list);
        }
      });
    }
  },
  created() {
    this.getAreaList();
  }
};
</script>
<style lang="scss">
.monitor-data{
  .amap-info-close{
    display: none;
  }
  .car-icon {
    width: 32px;
    height: 30px;
    fill: currentColor;
    overflow: hidden;
  }
}  
</style>
<style lang="scss" scoped>
.monitor-data{
    height: 100%;
    display: flex;
    flex-direction: column;
    /deep/ .map-tool{
      display: none;
    }
    .content{
      flex-grow: 1;
      display: flex;
      // &>div{
      //   flex:1
      // }
      .left{
        width: 30%;
      }
      .right{
        width: 70%;
      }
    }
  .result{
    font-size: 17px;
    /* margin-bottom: 10px; */
    padding: 5px;
    padding-bottom: 0;
  }
  .item{
    padding: 10px;
    font-size: 18px;
    display: flex;
    padding-bottom: 0;

  }   
  .box{
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    padding-bottom: 10px;
    margin-bottom: 10px;
    &>.item{
        // border-bottom:1px solid #ccc;
    }
    
  }
}
</style>
